import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
// 只保留一次 ElMessage 和 ElMessageBox 的导入
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  RefreshLeft,
  RefreshRight,
  View,
  Document,
  Delete,
  Upload,
  Download,
  Search,
  Picture,
  EditPen,
  Goods,
  Menu,
  Ticket,
  Timer,
  User,
  Wallet,
  Back
} from '@element-plus/icons-vue'

// 导入编辑器核心和组件
import { createDiyEditor } from '@/components/diy/shared/editor-core.js'
import { COMPONENT_TYPES, COMPONENT_CATEGORIES, COMPONENT_META } from '@/components/diy/shared/constants.js'

// 导入组件
import SearchBlock from '@/components/diy/vue3/components/SearchBlock.vue'
import ImageBanner from '@/components/diy/vue3/components/ImageBanner.vue'
import TitleText from '@/components/diy/vue3/components/TitleText.vue'
import GoodsCard from '@/components/diy/vue3/components/GoodsCard.vue'
import GoodsList from '@/components/diy/vue3/components/GoodsList.vue'
import MenuGrid from '@/components/diy/vue3/components/MenuGrid.vue'
import MenuList from '@/components/diy/vue3/components/MenuList.vue'
import CouponCard from '@/components/diy/vue3/components/CouponCard.vue'
import SeckillBlock from '@/components/diy/vue3/components/SeckillBlock.vue'
import GrouponBlock from '@/components/diy/vue3/components/GrouponBlock.vue'
import UserCard from '@/components/diy/vue3/components/UserCard.vue'
import UserWallet from '@/components/diy/vue3/components/UserWallet.vue'
import UserCoupon from '@/components/diy/vue3/components/UserCoupon.vue'
import Notice from '@/components/diy/vue3/components/Notice.vue'
import RichText from '@/components/diy/vue3/components/RichText.vue'
import Video from '@/components/diy/vue3/components/Video.vue'
import GraphicNavigation from '@/components/diy/vue3/components/GraphicNavigation.vue'
import TabBar from '@/components/diy/vue3/components/TabBar.vue'
import MagicCube from '@/components/diy/vue3/components/MagicCube.vue'
import AuxiliarySegmentation from '@/components/diy/vue3/components/AuxiliarySegmentation.vue'
import StoreInformation from '@/components/diy/vue3/components/StoreInformation.vue'
import Follow from '@/components/diy/vue3/components/Follow.vue'
import Suspension from '@/components/diy/vue3/components/Suspension.vue'
import OnlineService from '@/components/diy/vue3/components/OnlineService.vue'

// 导入属性面板
import PageConfigPanel from '@/components/diy/vue3/properties/PageConfigPanel.vue'
import SearchBlockPanel from '@/components/diy/vue3/properties/SearchBlockPanel.vue'
import ImageBannerPanel from '@/components/diy/vue3/properties/ImageBannerPanel.vue'
import TitleTextPanel from '@/components/diy/vue3/properties/TitleTextPanel.vue'
import GoodsCardPanel from '@/components/diy/vue3/properties/GoodsCardPanel.vue'
import GoodsListPanel from '@/components/diy/vue3/properties/GoodsListPanel.vue'
import MenuGridPanel from '@/components/diy/vue3/properties/MenuGridPanel.vue'
import MenuListPanel from '@/components/diy/vue3/properties/MenuListPanel.vue'
import CouponCardPanel from '@/components/diy/vue3/properties/CouponCardPanel.vue'
import SeckillBlockPanel from '@/components/diy/vue3/properties/SeckillBlockPanel.vue'
import GrouponBlockPanel from '@/components/diy/vue3/properties/GrouponBlockPanel.vue'
import UserCardPanel from '@/components/diy/vue3/properties/UserCardPanel.vue'
import UserWalletPanel from '@/components/diy/vue3/properties/UserWalletPanel.vue'
import UserCouponPanel from '@/components/diy/vue3/properties/UserCouponPanel.vue'
import NoticePanel from '@/components/diy/vue3/properties/NoticePanel.vue'
import RichTextPanel from '@/components/diy/vue3/properties/RichTextPanel.vue'
import VideoPanel from '@/components/diy/vue3/properties/VideoPanel.vue'
import GraphicNavigationPanel from '@/components/diy/vue3/properties/GraphicNavigationPanel.vue'
import TabBarPanel from '@/components/diy/vue3/properties/TabBarPanel.vue'
import MagicCubePanel from '@/components/diy/vue3/properties/MagicCubePanel.vue'
import AuxiliarySegmentationPanel from '@/components/diy/vue3/properties/AuxiliarySegmentationPanel.vue'
import StoreInformationPanel from '@/components/diy/vue3/properties/StoreInformationPanel.vue'
import FollowPanel from '@/components/diy/vue3/properties/FollowPanel.vue'
import SuspensionPanel from '@/components/diy/vue3/properties/SuspensionPanel.vue'
import OnlineServicePanel from '@/components/diy/vue3/properties/OnlineServicePanel.vue'

export function useDesignTempLogic() {
  // 创建两个独立的编辑器实例
  const editors = {
    home: createDiyEditor({
      pageTitle: '首页',
      backgroundColor: '#ffffff',
      margin: 0
    }),
    user: createDiyEditor({
      pageTitle: '用户中心',
      backgroundColor: '#ffffff',
      margin: 0
    })
  }

  // 当前活动页面类型
  const currentPageType = ref('home')

  // 当前活动编辑器
  // 当前活动编辑器 - 使用计算属性确保始终有值
  const activeEditor = computed(() => {
    return currentPageType.value === 'home' ? editors.home : editors.user
  })

  // 组件映射
  const componentMap = {
    [COMPONENT_TYPES.SEARCH_BLOCK]: SearchBlock,
    [COMPONENT_TYPES.IMAGE_BANNER]: ImageBanner,
    [COMPONENT_TYPES.TITLE_TEXT]: TitleText,
    [COMPONENT_TYPES.GOODS_CARD]: GoodsCard,
    [COMPONENT_TYPES.GOODS_LIST]: GoodsList,
    [COMPONENT_TYPES.MENU_GRID]: MenuGrid,
    [COMPONENT_TYPES.MENU_LIST]: MenuList,
    [COMPONENT_TYPES.COUPON_CARD]: CouponCard,
    [COMPONENT_TYPES.SECKILL_BLOCK]: SeckillBlock,
    [COMPONENT_TYPES.GROUPON_BLOCK]: GrouponBlock,
    [COMPONENT_TYPES.USER_CARD]: UserCard,
    [COMPONENT_TYPES.USER_WALLET]: UserWallet,
    [COMPONENT_TYPES.USER_COUPON]: UserCoupon,
    [COMPONENT_TYPES.NOTICE]: Notice,
    [COMPONENT_TYPES.RICH_TEXT]: RichText,
    [COMPONENT_TYPES.VIDEO]: Video,
    [COMPONENT_TYPES.GRAPHIC_NAVIGATION]: GraphicNavigation,
    [COMPONENT_TYPES.TAB_BAR]: TabBar,
    [COMPONENT_TYPES.MAGIC_CUBE]: MagicCube,
    [COMPONENT_TYPES.AUXILIARY_SEGMENTATION]: AuxiliarySegmentation,
    [COMPONENT_TYPES.STORE_INFORMATION]: StoreInformation,
    [COMPONENT_TYPES.FOLLOW]: Follow,
    [COMPONENT_TYPES.SUSPENSION]: Suspension,
    [COMPONENT_TYPES.ONLINE_SERVICE]: OnlineService
  }

  // 属性面板映射
  const propertyPanelMap = {
    [COMPONENT_TYPES.SEARCH_BLOCK]: SearchBlockPanel,
    [COMPONENT_TYPES.IMAGE_BANNER]: ImageBannerPanel,
    [COMPONENT_TYPES.TITLE_TEXT]: TitleTextPanel,
    [COMPONENT_TYPES.GOODS_CARD]: GoodsCardPanel,
    [COMPONENT_TYPES.GOODS_LIST]: GoodsListPanel,
    [COMPONENT_TYPES.MENU_GRID]: MenuGridPanel,
    [COMPONENT_TYPES.MENU_LIST]: MenuListPanel,
    [COMPONENT_TYPES.COUPON_CARD]: CouponCardPanel,
    [COMPONENT_TYPES.SECKILL_BLOCK]: SeckillBlockPanel,
    [COMPONENT_TYPES.GROUPON_BLOCK]: GrouponBlockPanel,
    [COMPONENT_TYPES.USER_CARD]: UserCardPanel,
    [COMPONENT_TYPES.USER_WALLET]: UserWalletPanel,
    [COMPONENT_TYPES.USER_COUPON]: UserCouponPanel,
    [COMPONENT_TYPES.NOTICE]: NoticePanel,
    [COMPONENT_TYPES.RICH_TEXT]: RichTextPanel,
    [COMPONENT_TYPES.VIDEO]: VideoPanel,
    [COMPONENT_TYPES.GRAPHIC_NAVIGATION]: GraphicNavigationPanel,
    [COMPONENT_TYPES.TAB_BAR]: TabBarPanel,
    [COMPONENT_TYPES.MAGIC_CUBE]: MagicCubePanel,
    [COMPONENT_TYPES.AUXILIARY_SEGMENTATION]: AuxiliarySegmentationPanel,
    [COMPONENT_TYPES.STORE_INFORMATION]: StoreInformationPanel,
    [COMPONENT_TYPES.FOLLOW]: FollowPanel,
    [COMPONENT_TYPES.SUSPENSION]: SuspensionPanel,
    [COMPONENT_TYPES.ONLINE_SERVICE]: OnlineServicePanel
  }

  // 图标映射
  const iconMap = {
    search: Search,
    picture: Picture,
    title: EditPen,
    goods: Goods,
    menu: Menu,
    ticket: Ticket,
    timer: Timer,
    user: User,
    wallet: Wallet
  }

  // 分类名称映射
  const categoryNameMap = {
    [COMPONENT_CATEGORIES.BASIC]: '基础组件',
    [COMPONENT_CATEGORIES.GOODS]: '商品组件',
    [COMPONENT_CATEGORIES.MARKETING]: '营销组件',
    [COMPONENT_CATEGORIES.USER]: '用户组件'
  }

  // 响应式数据
  const activeCategory = ref(COMPONENT_CATEGORIES.BASIC)
  const activePropertyTab = ref('page')
  const previewVisible = ref(false)
  const importVisible = ref(false)
  const importFile = ref(null)
  const uploadRef = ref(null)
  const dragIndex = ref(-1)
  const dropPosition = ref(-1)
  const offsetY = ref(0)
  const componentRefs = ref([])
  const componentLabels = ref([])
  const pageContentRef = ref(null)
  const syncScrollRef = ref(null)
  const lastScrollTop = ref(0)
  const previewAreaRef = ref(null)
  const previewContainerRef = ref(null)
  const phoneContainerRef = ref(null)
  const componentLabelStyle = ref({})
  const activeComponent = ref(null)
  // 临时标签状态
  const isTempLabelShow = ref(false)
  const tempLabelStyle = ref({})
  const tempLabelTargetIndex = ref(-1)
  const tempLabelComponentName = ref('')
  let isDragSortMode = ref(false)

  // 分离TabBar组件和其他组件
  const nonTabBarComponents = computed(() => {
    return activeEditor.value.state.components.filter(component => component.type !== COMPONENT_TYPES.TAB_BAR)
  })

  const tabBarComponents = computed(() => {
    return activeEditor.value.state.components.filter(component => component.type === COMPONENT_TYPES.TAB_BAR)
  })

  // 获取非TabBar组件在原始列表中的索引
  function getOriginalIndex(nonTabBarIndex) {
    let originalIndex = 0
    let nonTabBarCount = 0

    for (let i = 0; i < activeEditor.value.state.components.length; i++) {
      if (activeEditor.value.state.components[i].type !== COMPONENT_TYPES.TAB_BAR) {
        if (nonTabBarCount === nonTabBarIndex) {
          originalIndex = i
          break
        }
        nonTabBarCount++
      }
    }
    return originalIndex
  }

  // 获取TabBar组件在原始列表中的索引
  function getTabBarOriginalIndex(tabBarIndex) {
    let originalIndex = 0
    let tabBarCount = 0

    for (let i = 0; i < activeEditor.value.state.components.length; i++) {
      if (activeEditor.value.state.components[i].type === COMPONENT_TYPES.TAB_BAR) {
        if (tabBarCount === tabBarIndex) {
          originalIndex = i
          break
        }
        tabBarCount++
      }
    }
    return originalIndex
  }

  // 计算组件标签位置
  const componentLabelPositions = computed(() => {
    const positions = []
    if (!phoneContainerRef.value || !previewAreaRef.value) {
      return positions
    }

    const phoneContainerRect = phoneContainerRef.value.getBoundingClientRect()
    const previewAreaRect = previewAreaRef.value.getBoundingClientRect()
    const labelLeft = phoneContainerRect.left - previewAreaRect.left - 120

    // 如果有组件，计算每个组件标签的位置
    if (activeEditor.value.state.components.length > 0) {
      // 获取预览区域的滚动偏移量
      const previewAreaScrollTop = previewAreaRef.value.scrollTop || 0

      for (let i = 0; i < activeEditor.value.state.components.length; i++) {
        if (componentRefs.value[i]) {
          const componentEl = componentRefs.value[i]
          const componentRect = componentEl.getBoundingClientRect()

          // 计算标签顶部位置（组件中间位置）- 考虑滚动偏移量
          const labelTop = componentRect.top - previewAreaRect.top + componentRect.height / 2 + previewAreaScrollTop

          positions[i] = {
            left: `${labelLeft}px`,
            top: `${labelTop}px`,
            transform: 'translateY(-50%)',
            display: 'flex',
            transition: 'all 0.1s ease',
            backgroundColor: activeEditor.value.state.selectedComponentIndex === i ? '#409eff' : '#909399'
          }
        }
      }
    }
    return positions
  })

  // 计算选中组件删除按钮的位置
  const selectedDeleteBtnPosition = computed(() => {
    if (activeEditor.value.state.selectedComponentIndex === null ||
        !componentRefs.value[activeEditor.value.state.selectedComponentIndex] ||
        !phoneContainerRef.value ||
        !previewAreaRef.value) {
      return { display: 'none' }
    }

    const selectedIndex = activeEditor.value.state.selectedComponentIndex
    const componentEl = componentRefs.value[selectedIndex]
    const componentRect = componentEl.getBoundingClientRect()

    const phoneContainerRect = phoneContainerRef.value.getBoundingClientRect()
    const previewAreaRect = previewAreaRef.value.getBoundingClientRect()

    // 获取预览区域的滚动偏移量
    const previewAreaScrollTop = previewAreaRef.value.scrollTop || 0

    // 计算删除按钮位置（组件右上角）
    const btnLeft = phoneContainerRect.right - previewAreaRect.left - 10
    const btnTop = componentRect.top - previewAreaRect.top + previewAreaScrollTop - 12

    return {
      left: `${btnLeft}px`,
      top: `${btnTop}px`,
      display: 'flex'
    }
  })

  // 计算属性
  const categorizedComponents = computed(() => {
    const result = {}
    Object.values(COMPONENT_CATEGORIES).forEach(category => {
      result[category] = []
    })
    Object.entries(COMPONENT_META).forEach(([type, meta]) => {
      if (result[meta.category]) {
        result[meta.category].push({ ...meta, type })
      }
    })
    return result
  })

  // 方法
  function getComponentType(type) {
    return componentMap[type] || null
  }

  function getPropertyPanelType(type) {
    return propertyPanelMap[type] || null
  }

  function getIconComponent(iconName) {
    return iconMap[iconName] || Document
  }

  function getCategoryName(category) {
    return categoryNameMap[category] || category
  }

  // 计算单个组件标签位置
  function getComponentLabelStyle(index) {
    if (index === -1 || !componentRefs.value[index] || !phoneContainerRef.value) {
      return {}
    }

    try {
      const componentEl = componentRefs.value[index]
      if (!componentEl) return {}

      const componentRect = componentEl.getBoundingClientRect()
      const phoneContainerRect = phoneContainerRef.value.getBoundingClientRect()
      const previewAreaRect = previewAreaRef.value.getBoundingClientRect()
      const pageContentRect = pageContentRef.value.getBoundingClientRect()

      // 计算组件相对于页面内容的位置
      const relativeToPageTop = componentRect.top - pageContentRect.top

      // 计算页面内容相对于手机容器的位置
      const pageContentRelativeToPhoneTop = pageContentRect.top - phoneContainerRect.top

      // 计算组件相对于手机容器的总位置
      const totalRelativeTop = pageContentRelativeToPhoneTop + relativeToPageTop

      // 获取预览区域的滚动偏移量
      const previewAreaScrollTop = previewAreaRef.value.scrollTop || 0

      // 计算标签位置（组件左侧，考虑滚动偏移）
      const labelLeft = phoneContainerRect.left - previewAreaRect.left - 120
      const labelTop = totalRelativeTop + componentRect.height / 2 + previewAreaScrollTop

      return {
        left: `${labelLeft}px`,
        top: `${labelTop}px`,
        transform: 'translateY(-50%)',
        display: 'flex',
        transition: 'all 0.1s ease',
        backgroundColor: activeEditor.value.state.selectedComponentIndex === index ? '#409eff' : '#909399'
      }
    } catch (error) {
      console.error('计算组件标签位置出错:', error)
      return {}
    }
  }

  // 更新所有组件标签位置
  function updateComponentLabelPosition() {
    if (!phoneContainerRef.value || !previewAreaRef.value) return

    const positions = {}
    if (activeEditor.value.state.components.length > 0) {
      const phoneContainerRect = phoneContainerRef.value.getBoundingClientRect()
      const previewAreaRect = previewAreaRef.value.getBoundingClientRect()
      const labelLeft = phoneContainerRect.left - previewAreaRect.left - 120

      // 获取预览区域的滚动偏移量
      const previewAreaScrollTop = previewAreaRef.value.scrollTop || 0

      for (let i = 0; i < activeEditor.value.state.components.length; i++) {
        if (componentRefs.value[i]) {
          const componentEl = componentRefs.value[i]
          const componentRect = componentEl.getBoundingClientRect()

          // 计算标签顶部位置（组件中间位置）- 考虑滚动偏移量
          const labelTop = componentRect.top - previewAreaRect.top + componentRect.height / 2 + previewAreaScrollTop

          positions[i] = {
            left: `${labelLeft}px`,
            top: `${labelTop}px`,
            transform: 'translateY(-50%)',
            display: 'flex',
            transition: 'all 0.1s ease',
            backgroundColor: activeEditor.value.state.selectedComponentIndex === i ? '#409eff' : '#909399'
          }
        }
      }
    }
    componentLabelStyle.value = positions
  }

  // 显示临时标签
  function showTempLabel(targetIndex, componentName) {
    if (!phoneContainerRef.value || !previewAreaRef.value) return

    const phoneRect = phoneContainerRef.value.getBoundingClientRect()
    const previewAreaRect = previewAreaRef.value.getBoundingClientRect()

    tempLabelStyle.value = {
      left: `${phoneRect.right - previewAreaRect.left + 10}px`,
      top: `${phoneRect.top - previewAreaRect.top + phoneRect.height / 2}px`,
      transform: 'translateY(-50%)',
      display: 'flex',
      transition: 'all 0.1s ease'
    }

    tempLabelTargetIndex.value = targetIndex
    tempLabelComponentName.value = componentName
    isTempLabelShow.value = true
  }

  // 页面滚动时更新标签位置
  function handlePageScroll() {
    if (activeEditor.value.state.components.length > 0) {
      updateComponentLabelPosition()
    }
  }

  // 组件操作
  function handleAddComponent(type, componentName) {
    if (!type) {
      ElMessage.error('组件类型不能为空')
      return
    }
    if (isSingletonComponent(type) && hasSingletonComponent(type)) {
      ElMessage.warning('该组件只能添加一个')
      return
    }

    const newIndex = activeEditor.value.state.components.length
    // 1. 先显示临时标签
    showTempLabel(newIndex, componentName)
    // 2. 再添加组件
    activeEditor.value.addComponent(type)

    // 3. 组件渲染完成后，切换到正式标签
    nextTick(() => {
      activeEditor.value.selectComponent(newIndex) // 强制选中新组件
      nextTick(() => {
        updateComponentLabelPosition()
        nextTick(updateComponentLabelPosition)
      })
    })
  }

  function handleSelectComponent(index) {
    activeEditor.value.selectComponent(index)
    activePropertyTab.value = 'component'
  }

  function handleUpdatePageConfig(updates) {
    activeEditor.value.updatePageConfig(updates)
  }

  function handleUpdateComponentData(updates) {
    const index = activeEditor.value.state.selectedComponentIndex
    if (index >= 0) {
      activeEditor.value.updateComponent(index, { data: updates })
    }
  }

  function handleUpdateComponentStyles(updates) {
    const index = activeEditor.value.state.selectedComponentIndex
    if (index >= 0) {
      const component = activeEditor.value.state.components[index]
      // 创建新的样式对象，确保响应式更新
      const newStyles = { ...component.styles, ...updates }
      activeEditor.value.updateComponent(index, { styles: newStyles })
    }
  }

  function handleUndo() {
    activeEditor.value.undo()
    nextTick(updateComponentLabelPosition)
  }

  function handleRedo() {
    activeEditor.value.redo()
    nextTick(updateComponentLabelPosition)
  }

  function handlePreview() {
    previewVisible.value = true
  }

  function handleSave() {
    ElMessage.success('保存成功')
  }

  function handleClear() {
    ElMessageBox.confirm('确定要清空所有组件吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      while (activeEditor.value.state.components.length > 0) {
        activeEditor.value.removeComponent(0)
      }
      // 清空时隐藏所有标签
      isTempLabelShow.value = false
      componentLabelStyle.value = {}
      activeComponent.value = null
      ElMessage.success('已清空所有组件')
    })
  }

  function handleImport() {
    importVisible.value = true
  }

  function handleExport() {
    const jsonString = activeEditor.value.exportToJson()
    const blob = new Blob([jsonString], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `diy-page-${Date.now()}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  }

  function handleFileChange(file) {
    importFile.value = file.raw
  }

  function confirmImport() {
    if (!importFile.value) {
      ElMessage.error('请选择文件')
      return
    }
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const jsonString = e.target.result
        const success = activeEditor.value.importFromJson(jsonString)
        if (success) {
          ElMessage.success('导入成功')
          importVisible.value = false
          // 导入后如果有组件，自动显示第一个组件的正式标签
          if (activeEditor.value.state.components.length > 0) {
            nextTick(() => {
              activeEditor.value.selectComponent(0)
              nextTick(updateComponentLabelPosition)
            })
          }
        } else {
          ElMessage.error('导入失败，请检查文件格式')
        }
      } catch (error) {
        console.error('导入文件解析错误:', error)
        ElMessage.error('导入失败，文件格式错误')
      }
    }
    reader.readAsText(importFile.value)
  }

  // 拖拽相关
  function handleDragStart(component, event) {
    event.dataTransfer.setData('componentType', component.type)
    event.dataTransfer.setData('componentName', component.name)
  }

  function handleDragOver(event, index) {
    event.preventDefault()
    // 计算放置位置
    const rect = event.currentTarget.getBoundingClientRect()
    const midY = rect.top + rect.height / 2
    dropPosition.value = event.clientY < midY ? index : index + 1
  }

  function handleDrop(event, index) {
    event.preventDefault()
    const componentType = event.dataTransfer.getData('componentType')
    const componentMeta = COMPONENT_META[componentType]
    if (isSingletonComponent(componentType) && hasSingletonComponent(componentType)) {
      ElMessage.warning('该组件只能添加一个')
      return
    }

    let insertIndex = index
    if (dropPosition.value >= 0) {
      insertIndex = dropPosition.value
    }

    // 拖拽添加时也显示临时标签
    showTempLabel(insertIndex, componentMeta?.name || '组件')
    activeEditor.value.addComponent(componentType, {}, insertIndex)

    nextTick(() => {
      handleSelectComponent(insertIndex)
      nextTick(updateComponentLabelPosition)
    })

    dragIndex.value = -1
    dropPosition.value = -1
  }

  function handleDragEnd() {
    dragIndex.value = -1
    dropPosition.value = -1
    offsetY.value = 0
  }

  // 组件编辑
  function handleDeleteComponent(index) {
    // 先清除组件引用
    if (componentRefs.value[index]) {
      componentRefs.value[index] = null
    }

    // 执行删除操作
    activeEditor.value.removeComponent(index)
    ElMessage.success('删除成功')
    // 删除时隐藏所有标签
    isTempLabelShow.value = false
    componentLabelStyle.value = {}
    activeComponent.value = null
    // 如果还有组件，自动选中第一个
    if (activeEditor.value.state.components.length > 0) {
      nextTick(() => {
        handleSelectComponent(0)
      })
    }
  }

  function handleMoveUpLayer(index) {
    if (index > 0) {
      activeEditor.value.moveComponent(index, index - 1)
      ElMessage.success('上移成功')
      nextTick(updateComponentLabelPosition)
    }
  }

  function handleMoveDownLayer(index) {
    if (index < activeEditor.value.state.components.length - 1) {
      activeEditor.value.moveComponent(index, index + 1)
      ElMessage.success('下移成功')
      nextTick(updateComponentLabelPosition)
    }
  }

  // 单例组件检查
  function isSingletonComponent(type) {
    const meta = COMPONENT_META[type]
    return meta && meta.singleton === true
  }

  function hasSingletonComponent(type) {
    return activeEditor.value.state.components.some(component => component.type === type)
  }

  // 返回上一页
  function handlePrevious() {
    // 这里可以添加路由跳转逻辑
    console.log('返回上一页')
  }

  // 组件拖拽排序
  function toggleDragSortMode() {
    isDragSortMode.value = !isDragSortMode.value
    if (isDragSortMode.value) {
      ElMessage.info('拖拽排序模式已开启，可以拖动组件调整顺序')
    } else {
      ElMessage.info('拖拽排序模式已关闭')
    }
  }

  function handleComponentDragStart(index, event) {
    dragIndex.value = index
    offsetY.value = event.offsetY
    event.dataTransfer.effectAllowed = 'move'
  }

  function handleComponentDragOver(event) {
    event.preventDefault()
    event.dataTransfer.dropEffect = 'move'
  }

  function handleComponentDrop(targetIndex, event) {
    event.preventDefault()
    if (dragIndex.value === -1) return

    const sourceIndex = dragIndex.value

    if (sourceIndex === targetIndex) return

    // 使用编辑器的移动组件方法
    activeEditor.value.moveComponent(sourceIndex, targetIndex)

    // 更新选中组件
    nextTick(() => {
      handleSelectComponent(targetIndex)
      nextTick(updateComponentLabelPosition)
    })

    ElMessage.success('组件顺序已更新')
  }

  // 处理窗口大小变化
  function handleResize() {
    nextTick(updateComponentLabelPosition)
  }

  // 处理鼠标滚轮事件
  function handleWheel(e) {
    // 使用 passive 事件监听器时，不能调用 preventDefault
    // 改为使用其他方式处理滚动
    if (pageContentRef.value) {
      const scrollAmount = e.deltaY > 0 ? 50 : -50
      pageContentRef.value.scrollTop += scrollAmount
    }
    return false
  }

  // 页面类型切换
  function handlePageTypeChange(type) {
    // 切换页面类型
    currentPageType.value = type
    activeEditor.value = type === 'home' ? editors.home : editors.user

    // 更新UI
    nextTick(() => {
      updateComponentLabelPosition()
    })
  }

  // 导出设计数据
  function exportDesign() {
    return {
      home: {
        components: editors.home.state.components,
        pageConfig: editors.home.state.pageConfig
      },
      user: {
        components: editors.user.state.components,
        pageConfig: editors.user.state.pageConfig
      }
    }
  }

  // 导入设计数据
  function importDesign(designData) {
    if (designData.home) {
      editors.home.state.components = designData.home.components || []
      editors.home.updatePageConfig(designData.home.pageConfig || {})
    }

    if (designData.user) {
      editors.user.state.components = designData.user.components || []
      editors.user.updatePageConfig(designData.user.pageConfig || {})
    }

    // 更新当前页面
    nextTick(() => {
      updateComponentLabelPosition()
    })
  }

  // 生命周期
  onMounted(() => {
    // 使用 nextTick 确保 DOM 已渲染
    nextTick(() => {
      if (pageContentRef.value) {
        pageContentRef.value.addEventListener('scroll', handlePageScroll)
      }
    })
    window.addEventListener('resize', handleResize)

    // 监听组件选择变化
    watch(() => activeEditor.value.state.selectedComponentIndex, () => {
      updateComponentLabelPosition()
    })

    // 监听组件列表变化
    watch(() => activeEditor.value.state.components.length, (newLength) => {
      if (newLength > 0) {
        nextTick(updateComponentLabelPosition)
      } else {
        // 没有组件时隐藏标签
        isTempLabelShow.value = false
        componentLabelStyle.value = {}
        activeComponent.value = null
      }
    })
  })

  // 清理
  onUnmounted(() => {
    if (pageContentRef.value) {
      pageContentRef.value.removeEventListener('scroll', handlePageScroll)
    }
    window.removeEventListener('resize', handleResize)
  })

  // 暴露所有需要在模板中使用的变量和方法
  return {
    // 编辑器相关
    editors,
    activeEditor,
    currentPageType,

    // 响应式数据
    activeCategory,
    activePropertyTab,
    previewVisible,
    importVisible,
    importFile,
    uploadRef,
    dragIndex,
    dropPosition,
    offsetY,
    componentRefs,
    componentLabels,
    pageContentRef,
    syncScrollRef,
    lastScrollTop,
    previewAreaRef,
    previewContainerRef,
    phoneContainerRef,
    componentLabelStyle,
    activeComponent,
    isTempLabelShow,
    tempLabelStyle,
    tempLabelTargetIndex,
    tempLabelComponentName,
    isDragSortMode,

    // 计算属性
    nonTabBarComponents,
    tabBarComponents,
    componentLabelPositions,
    selectedDeleteBtnPosition,
    categorizedComponents,

    // 方法
    getComponentType,
    getPropertyPanelType,
    getIconComponent,
    getCategoryName,
    getComponentLabelStyle,
    updateComponentLabelPosition,
    showTempLabel,
    handlePageScroll,
    handleAddComponent,
    handleSelectComponent,
    handleUpdatePageConfig,
    handleUpdateComponentData,
    handleUpdateComponentStyles,
    handleUndo,
    handleRedo,
    handlePreview,
    handleSave,
    handleClear,
    handleImport,
    handleExport,
    handleFileChange,
    confirmImport,
    handleDragStart,
    handleDragOver,
    handleDrop,
    handleDragEnd,
    handleDeleteComponent,
    handleMoveUpLayer,
    handleMoveDownLayer,
    isSingletonComponent,
    hasSingletonComponent,
    handlePrevious,
    toggleDragSortMode,
    handleComponentDragStart,
    handleComponentDragOver,
    handleComponentDrop,
    handleResize,
    handleWheel,
    handlePageTypeChange,
    exportDesign,
    importDesign,
    // 工具函数
    getOriginalIndex,
    getTabBarOriginalIndex
  }
}